package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.*;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 超时控制示例
 *
 * @author yangyunjiao
 */
public class TimeoutExample {
    public static void main(String[] args) throws InterruptedException {
        ListeningExecutorService executor =
                MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());

        ListenableFuture<String> future = executor.submit(() -> {
            Thread.sleep(3000); // 模拟长时间运行的任务
            return "任务结果";
        });

        // 添加带超时的回调
        Futures.addCallback(future, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("收到结果: " + result);
            }

            @Override
            public void onFailure(Throwable t) {
                if (t instanceof TimeoutException) {
                    System.err.println("任务超时");
                    future.cancel(true); // 取消任务
                } else {
                    System.err.println("任务失败: " + t.getMessage());
                }
            }
        }, executor);

        // 在主线程中等待结果（带超时）
        try {
            String result = future.get(2, TimeUnit.SECONDS); // 2秒超时
            System.out.println("主线程收到结果: " + result);
        } catch (TimeoutException e) {
            System.err.println("主线程等待超时");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}
